library common_tool;

import 'dart:async';

class LocalClock {

  static int currentTimeStamp = -1;
  static Timer? globalTimer;

  static void startTimer() {

    globalTimer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      if (currentTimeStamp < 0) {
        return;
      }

      currentTimeStamp += 1000;
    });
  }

  static void syncTime(int? timeStamp) {
    if (timeStamp == null) {
      return;
    }
    if (globalTimer == null) {
      startTimer();
    }
    currentTimeStamp = timeStamp;
  }

  /// 因为本地时间设置可能有问题，所以统一转UTC
  static DateTime? getNetworkUTCDateTime() {
    if (currentTimeStamp < 0) {
      return null;
    }
    return DateTime.fromMillisecondsSinceEpoch(currentTimeStamp).toUtc();
  }

  /// 如果当前项目不支持通过响应体设置服务器时间
  /// 就判断为不支持本地时钟
  static bool canUseLocalClock() {
    return currentTimeStamp > 0;
  }
}